<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /*
      +1-2/2*3 +
      思路：计算器问题一般会在前面默认加个+号，符号数字两个为一组，一起计算
      */
      var calculate = function (s) {
        s = s + '+'
        let count = 0
        //栈里永远存放可直接相加的数字 (-代表负数)
        let stack = []
        let pre = '+'
        for (let i = 0; i < s.length; i++) {
          if (s[i] == ' ') continue
          //遇到数字,可能有多位
          if (+s[i] >= 0 && +s[i] <= 9) {
            count = count * 10 + Number(s[i])
          } else {
            //当前遇到了符号需要判断之前的符号
            switch (pre) {
              case '+':
                stack.push(count)
                break
              case '-':
                stack.push(-count)
                break
              case '*':
                let num = stack.pop()
                stack.push(num * count)
                break
              case '/':
                let n = stack.pop()
                stack.push(parseInt(n / count))
                break
            }
            pre = s[i]
            count = 0
          }
        }
        return stack.reduce((pre, cur) => (pre += cur))
      }
    </script>
  </body>
</html>
